<template>
  <view class="search">
    <!-- 搜索框 -->
    <view class="px-[24rpx] py-[14rpx] bg-white">
      <u-search v-model="keyword" placeholder="请输入关键词搜索" height="72" @search="handleSearch" @custom="handleSearch" @clear="search.searching = false"></u-search>
    </view>

    <!-- 搜索 -->
    <view class="search-content">
      <!--  -->
      <suggest v-show="!search.searching" @search="handleSearch" @clear="handleClear" :hot_search="search.hot_search" :his_search="search.his_search"></suggest>

      <!--  -->
      <view class="search-content-s pt-[20rpx]" v-show="search.searching">
        <z-paging ref="paging" v-model="search.result" @query="queryList" :fixed="false" loading-more-no-more-text="我也是有底线的！" auto-show-back-to-top height="100%">
          <block v-for="item in search.result" :key="item.id"><news-card :item="item" :newsId="item.id"></news-card></block>
        </z-paging>
      </view>
    </view>
  </view>
</template>
<script>
import cache from '@/utils/cache';
import { mapState } from 'vuex';
import suggest from './component/suggest.vue';
import { HISTORY } from '@/config/cachekey';
export default {
  components: { suggest },
  data() {
    return {
      search: {
        hot_search: {
          data: [],
          status: 1
        },
        his_search: [],
        result: [],
        searching: false
      },
      keyword: ''
    };
  },
  methods: {
    handleSearch(value) {
      this.keyword = value;
      if (this.keyword) {
        if (!this.search.his_search.includes(this.keyword)) {
          this.search.his_search.unshift(this.keyword);
          cache.set(HISTORY, this.search.his_search);
        }
      }
      this.$refs.paging.reload();
      this.search.searching = true;
    },
    async getHotSearchFunc() {
      try {
        this.search.hot_search = await uni.$u.api.getHotSearch();
      } catch (e) {
        //TODO handle the exception
        console.log('获取热门搜索失败=>', e);
      }
    },
    async handleClear() {
      const resModel = await uni.showModal({
        title: '温馨提示',
        content: '是否清空历史记录？'
      });
      if (resModel.confirm) {
        cache.set(HISTORY, '');
        this.search.his_search = [];
      }
    },
    async queryList(page_no, page_size) {
      try {
        const { lists } = await uni.$u.api.getArticleList({
          keyword: this.keyword,
          page_no,
          page_size
        });
        this.$refs.paging.complete(lists);
      } catch (e) {
        console.log('报错=>', e);
        //TODO handle the exception
        this.$refs.paging.complete(false);
      }
    }
  },
  onLoad() {
    this.getHotSearchFunc();
    this.search.his_search = cache.get(HISTORY) || [];
  }
};
</script>

<style lang="scss" scoped>
.search {
  &-content {
    height: calc(100vh - 46px - env(safe-area-inset-bottom));
    &-s {
      height: 100%;
    }
  }
}
</style>
